package com.example.common.utils;

import cn.hutool.jwt.JWT;
import com.example.demo.domain.UserInfo;

import javax.servlet.http.Cookie;

public class TokenCookieUtil {
    // 密钥
    private final static byte[] TOKEN_KEY = "LV2023-NIU-6039P-08409-8J0QH-2YR7F".getBytes();

    /**
     * 生成token
     */

    public static String createToken(UserInfo userInfo) {

        //创建并封装返回token
        String userid = userInfo.getUserid();
        return JWT.create()
                .setPayload("userId", userid)
                .setKey(TOKEN_KEY)
                .sign();
    }


    /**
     * 解密COOKIE 中的token
     * 返回UserId
     */
    public static String encodingToken(Cookie[] cookies) {
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals("token")) {
                    String token = cookie.getValue();
                    JWT jwt = JWT.of(token);
                    //解析获取token
                    return (String) jwt.getPayload("userId");
                }
            }
        }
        return null;
    }

    /**
     * token封装进Cookie
     *
     * @param token
     * @return
     */
    public static Cookie takeTokenToCookie(String token) {
        return new Cookie("token", token);
    }
}
